<template>
    <div class="container">
            <div class="login-wrapper">
                <div class="header">登录页面</div>
                <div class="form-wrapper">
                    <el-form 
                        :rules="easyrules"
                        ref="formRef"
                        :model="loginObj"
                    >
                    <el-form-item label="用户名"  prop="username" class="input-item">
                        <el-input v-model="loginObj.username" 
                        placeholder="请输入用户名"
                        autocomplete="off"/>
                    </el-form-item>
                    <br />
                    <el-form-item label="密码"  prop="userpass" class="input-item">
                        <el-input v-model="loginObj.userpass"  
                        type="password"
                        placeholder="请输入密码"
                        show-password
                        autocomplete="off"/>
                    </el-form-item>
                    <el-form-item>
                        <el-checkbox label="记住我" v-model="rememberMe"></el-checkbox>
                    </el-form-item>
                    <div class="login-page">
                        <el-form label-width="65px">
                        <el-form-item label="验证码">
                        <el-input placeholder="请输入验证码" v-model="sidentifyMode" clearable></el-input>
                        </el-form-item>
                        <!-- 使用验证码组件 -->
                        <div class="code" @click="refreshCode">
                        <SIdentify :identifyCode="identifyCode"></SIdentify>
                        </div>
                        <el-button class="btn" size="default" type="primary" @click="dologin">登录</el-button>
                        </el-form>
                    </div>
                    </el-form>
                </div>
            </div>
            <!-- 修改密码弹窗
            <el-dialog 
                title="修改密码" 
                :visible.sync="showChangePasswordDialog"
                width="400px"
            >
                <el-form>
                    <el-form-item label="原密码">
                        <el-input type="password" v-model="loginObj.userpass" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="新密码">
                        <el-input type="password" v-model="newPassword"></el-input>
                    </el-form-item>
                    <el-form-item label="确认新密码">
                        <el-input type="password" v-model="confirmPassword"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleChangePassword">保存修改</el-button>
                        <el-button @click="showChangePasswordDialog = false">取消</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog> -->
    </div>
</template>

<script setup>
import {reactive, ref,onMounted} from 'vue'
import easyapi from '../api'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox,ElDialog } from 'element-plus'
import SIdentify from '../views/Sidentify.vue'
import * as THREE from 'three';
//获取路由器
let $router = useRouter()
let sidentifyMode = ref('') //输入框验证码
let identifyCode = ref('') //图形验证码
let identifyCodes = ref('1234567890abcdefjhijklinopqrsduvwxyz') //验证码出现的数字和字母
 
//组件挂载
onMounted(() => {
  identifyCode.value = ''
  makeCode(identifyCodes.value, 4)
  // 页面加载时检查 localStorage 中是否有保存的用户信息
  const savedUser = localStorage.getItem("user") || sessionStorage.getItem("user")
  if (savedUser) {
    loginObj.value = JSON.parse(savedUser)
    rememberMe.value = true
  }
})
 
// 生成随机数
const randomNum = (min, max) => {
  max = max + 1
  return Math.floor(Math.random() * (max - min) + min)
}
// 随机生成验证码字符串
const makeCode = (o, l) => {
  for (let i = 0; i < l; i++) {
    identifyCode.value += o[randomNum(0, o.length)]
  }
}
// 更新验证码
const refreshCode = () => {
  identifyCode.value = ''
  makeCode(identifyCodes.value, 4)
}

const router = useRouter();
const loginObj = ref({});
const formRef = ref({});
//记住我状态
const rememberMe=ref(false);
// //控制弹出窗口的显示
// const showChangePasswordDialog=ref(false);
// //新密码
// const newPassword=ref('')
// //确认新密码
// const confirmPassword=ref('')

const dologin = async function () {
    formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                // 将验证码添加到登录对象中                
                let result = await easyapi.postForm("/api/dologin", loginObj.value);
                console.log(result);
                //const encryptedPassword=await easyapi.postForm("/api/login",loginObj.value);
                if (result.code === 200 && result.data) {
                    //验证验证码不为空
                    if (!sidentifyMode.value) {
                    ElMessage({ type: 'error', message: '验证码不能为空！' })
                    return
                    }
                    //验证验证码是否正确
                    if (sidentifyMode.value != identifyCode.value) {
                        ElMessage({ type: 'error', message: '验证码错误' })
                        refreshCode()
                        return
                    } else {
                        ElMessage({ type: 'success', message: '登录成功' })
                        $router.push('/easyb')
                    }
                    // 登录成功
                    // 存放 token
                    sessionStorage.setItem("easytoken", result.data);
                    if(rememberMe.value){
                        localStorage.setItem("user",JSON .stringify(loginObj.value))
                    }else{
                        sessionStorage.setItem("user",JSON.stringify(loginObj.value))
                    }
                    //存放用户名
                    sessionStorage.setItem("username",loginObj.value.username);
                    console.log(sessionStorage.getItem("username")+"++++++++++");
                    // 提示成功
                    // ElMessage({
                    //     type: 'success',
                    //     message: result.message
                    // });
                    setTimeout(function () {
                        // js代码跳转
                        router.push("/easyb");
                    }, 1000);
                } else {
                    // 登录失败
                    ElMessage({
                        type: 'error',
                        message:'登录失败，请检查您的用户名和密码。'
                    });
                }
            } catch (error) {
                // 捕获并处理请求中的任何异常
                console.error('登录请求失败:', error);
                ElMessage({
                    type: 'error',
                    message: '登录请求失败，请稍后再试。'
                });
            }
        } else {
            console.log('error submit!');
        }
    });
};
// const handleChangePassword=async ()=>{
//     if(newPassword.value!=confirmPassword.value){
//         ElMessage({type:'error',message:'新密码和确认密码不匹配'})
//         return
//     }
//     try{
//         let result=await easyapi.postForm("/api/change-password",{
//             username:loginObj.value.username,
//             oldPassword:loginObj.value.userpass,
//             newPassword:newPassword.value
//         })
//         if(result.code === 200){
//             ElMessage({type:'success',message:'密码修改成功，请重新登录'})
//             showChangePasswordDialog.value=false
//             loginObj.value.userpass=newPassword.value
//             $router.push('/login')
//         }else{
//             ElMessage({type:'error',message:result.message})
//         }
//     }catch(error){
//         console.error('修改密码请求失败：',error)
//         ElMessage({type:'error',message:'修改密码请求失败，请稍后再试。'})
//     }
// }
    const checkname=function(rule,value,callback){
        let reg = /^[A-Za-z\u4e00-\u9fa5]{2,15}$/;
        if(reg.test(loginObj.value.username)){
            callback();
        }else{
            callback(new Error('用户名应为2-15位中/英文'));
        }
        callback(new Error('事件触发了'))
    }
    const checkpass=function(rule,value,callback){
        let reg=/^[A-z]\w{5,11}$/;
        if(reg.test(loginObj.value.userpass)){
            callback();
        }else{
            callback(new Error('密码应为5-11为以字母开头的数字与字母的组合'));
        }
        callback(new Error('事件触发了'))
    }
    const easyrules=reactive({
        username:[{validator:checkname, trigger: 'blur'}],
        userpass:[{validator:checkpass, trigger: 'blur'}],
    })
</script>
 
<style lang="scss" scoped>
html {
    height: 100%;
}
body {
    height: 100%;
}
.container {
    /* margin-top: 5%; */
    height: 800px;
    width: 100%;
    background-image: linear-gradient(to right, #f4daec, #c8d8f4);
}
.login-wrapper {
    background-color: #fff;
    width: 400px;
    height: 750px;
    border-radius: 15px;
    padding: 0 50px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}
.header {
    font-size: 38px;
    font-weight: bold;
    text-align: center;
    line-height: 200px;
}
.input-item {
    display: block;
    width: 100%;
    margin-bottom: 20px;
    border: 0;
    padding: 10px;
    font-size: 15px;
    outline: none;
}
.input-item::placeholder {
    text-transform: uppercase;
}
.btn {
    text-align: center;
    padding: 10px;
    margin: 0 auto;
    width: 100%;
    margin-top: 40px;
    background-image: linear-gradient(to right, #c8d8f4, #f4daec);
    color: #fff;
}
.msg {
    text-align: center;
    line-height: 88px;
}
a {
    text-decoration-line: none;
    color: #abc1ee;
}

.login-page {
  border: 1.5px solid rgb(226, 112, 179);
  border-radius: 8px;
  width: 300px;
  margin: 0 auto;
  margin-top: 50px;
  padding: 20px;
  .code {
    text-align: center;
    margin-bottom: 10px;
  }
  .login_btn {
    width: 100%;
  }
} 
</style>